package com.fang.algorithm.zuo.linked;

/**
 * @author lingxiao.fang
 * @Desc 删除链表中的指定值
 * @createTime 2025/2/8 10:59
 */
public class Test02_RemoveLinkedListValue {
    public static class Node {
        public int value;
        public Node next;

        public Node(int value) {
            this.value = value;
        }
    }

    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(1);
        Node node5 = new Node(1);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
//        Node targetNode = removeValue(node1, 1);
        Node targetNode = removeValue2(node1, 1);
        printNode(targetNode);
    }

    private static Node removeValue2(Node head, int value) {
        // 处理头部节点为目标value
        while (head != null) {
            if (head.value != value) {
                break;
            }
            head = head.next;
        }
        // 处理后续节点
        Node pre = head;
        Node cur = head;
        while (cur != null) {
            if (cur.value == value) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }

    private static Node removeValue(Node head, int value) {
        Node targetNode = head;
        Node pre = head;
        while (head != null) {
            if (head.value == value) {
                if (targetNode.equals(head)) {
                    targetNode = targetNode.next;
                }
                pre.next = head.next;
            } else {
                pre = head;
            }
            head = head.next;
        }
        return targetNode;
    }

    private static void printNode(Node node) {
        while (node != null) {
            System.out.print(node.value + "->");
            node = node.next;
        }
        System.out.println();
    }
}
